package com.woniu.config;

import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;

import com.woniu.client.OrderClient;
import com.woniu.commons.model.Result;
import com.woniu.model.model.YGoodsOrder;
import com.woniu.model.param.PagePayParam;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

@Component
public class AlipayUtil {
    @Resource
    private AlipayClient alipayClient;
    @Resource
    private OrderClient orderCient;

    /**
     * 网页支付方法 参数:封装支付参数，需要包含订单号、支付金额、支付说明、详细描述（可选）、同步回调地址、异步回调地址
     */
    public String pagePay(PagePayParam param) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置参数
        String content = "{\"out_trade_no\":\""+param.getOrderId()+"\","+"\"total_amount\":\""+param.getMoney()+"\","+"\"subject\":\"" + param.getSubject()+"\","+"\"body\":\""+param.getBody()+"\","+"\"product_code\":\"FAST_INSTANT_TRADE_PAY\","+"\"time_expire\":\""+param.getTimeExpire()+"\"}";
        request.setBizContent(content);
        //设置同步回调和异步回调
        request.setReturnUrl(param.getReturnUrl());
        request.setNotifyUrl(param.getNotifyUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //判断支付宝响应结果
        if (response.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return response.getBody();
        }
        throw new Exception("发起支付失败");
    }


    public String refund(String orderNum) throws Exception {
        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        //设置外部订单编号
        String out_trade_no = orderNum;
        //设置退款金额
        Result<YGoodsOrder> oneId = orderCient.getOneId(orderNum);
        YGoodsOrder orderInfo = oneId.getData();

        if (orderInfo == null) {
            throw new Exception("此订单不存在");
        }
        double refund_amount = orderInfo.getPrice().doubleValue();
        //设置退款原因
        String refund_reason = "没有理由";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + UUID.randomUUID().toString() + "\"}");

        return alipayClient.execute(alipayRequest).getBody();
    }






}
